package 组合问题;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 组合总和
 * @date 2022/11/13 17:29
 */
public class Demo39 {
    List<List<Integer>> res=new ArrayList<>();
    LinkedList<Integer> path=new LinkedList<>();
    int sum=0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTrack(candidates,0,target);
       return res;
    }

    private void backTrack(int[] candidates, int startIndex, int target) {
        if(sum>target){
            return;
        }
        if(sum==target){
            ArrayList<Integer> temp=new ArrayList<>(path);
            res.add(temp);
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum=sum+candidates[i];
            backTrack(candidates, i, target);
            path.removeLast();
            sum=sum-candidates[i];
        }
    }
}
